import { Component, Input } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatToolbarModule } from '@angular/material/toolbar';
import { ToolbarAddressCmpComponent } from "../toolbar-address-cmp/toolbar-address-cmp.component";
import { CoreService } from '../../service/core.service';
import { FormsModule } from '@angular/forms';
import { MatMenuModule } from '@angular/material/menu';
import { auth, file, fileInfoBaseDto, folder, QueryDto } from 'ispace.core.main';
import { PropertiesCmpComponent } from '../properties-cmp/properties-cmp.component';
import { MatDialog } from '@angular/material/dialog';
import { FolderDetailsDto } from '../../dto/folderDetailsDto';
import { CommonModule } from '@angular/common';
import { CreateSymbolicLinkCmpComponent } from '../create-symbolic-link-cmp/create-symbolic-link-cmp.component';
import { DriverOperationDto } from 'ispace_doa';
import { MatInputModule } from '@angular/material/input';

@Component({
  selector: 'app-toolbar-cmp',
  standalone: true,
  imports: [MatToolbarModule, MatIconModule, MatButtonModule,MatMenuModule, MatDividerModule, ToolbarAddressCmpComponent,FormsModule,CommonModule,MatInputModule],
  templateUrl: './toolbar-cmp.component.html',
  styleUrl: './toolbar-cmp.component.scss'
})
export class ToolbarCmpComponent {
constructor(public coreSvc: CoreService, public dialog: MatDialog) { 
  this.load_templates();
  this.coreSvc.query.subscribe(s => {
    this.query = s; 
  })

  this.coreSvc.path.subscribe(s => {
    this.init_ext_operations();
  })

}

// 查询模块 //
query: string = "";
search() {
  this.coreSvc.setQuery(this.query);
}
 
  logout() {
    auth.logout();
    window.location.reload();
  }
  
  isDesktop = () => {  
    return this.coreSvc.env.value=='alone'
  }

  @Input() folder?: FolderDetailsDto

 

  createFolder() {
    let maxIndex = 0;
    this.coreSvc.currentFiles.value.filter(s => s.isDir && s.name!.startsWith("新建文件夹"))
      .forEach(s => {
        let indexStr = s.name!.replace("新建文件夹", "").trim();
        let index = Number(indexStr);
        if (index > maxIndex) {
          maxIndex = index;
        }
      });
    maxIndex++;
    let folderName = "新建文件夹" + maxIndex;
    folder.create(this.coreSvc.path.value.path, folderName).subscribe(s => {
      this.refresh();
    }, e => {
      console.error(e);
    })
  }

  createSymbolicLink() {
    this.dialog.open(CreateSymbolicLinkCmpComponent, {
      data: {
        path: this.coreSvc.path.value.path,
        type: "createSymbolicLink"
      },
    }).afterClosed().subscribe(result => {
      if (result) {
        this.refresh();
      }    
    });
  }

 


  refresh() {
    this.coreSvc.refresh();
  }
 
  /*** 新建文件 ***/
  createFile_basePath = "/Desktop/.ispace/new_decument_template";
  createFile_templates: fileInfoBaseDto[] = [];

  load_templates() {
    if (this.createFile_templates.length > 0) {
      this.createFile_templates = [];
    }
    let query = new QueryDto();
    query.path = this.createFile_basePath;
    folder.children(query).subscribe(s => {
      this.createFile_templates = s.filter(s => !s.isDir);
    })
  }

  createFile(template: fileInfoBaseDto) {

    // 名称 和 后缀
    let data = template.name!.split(".");
    let name = data[0];
    let ext = data[1];

    let maxIndex = 0;
    this.coreSvc.currentFiles.value.filter(s => !s.isDir && s.name!.endsWith('.' + ext) && s.name!.startsWith(name))
      .forEach(s => {
        let indexStr = s.name!.replace(name!, "").replace('.' + ext, "").trim();
        let index = Number(indexStr);
        if (index > maxIndex) {
          maxIndex = index;
        }
      });
    maxIndex++;
    let createName = name + maxIndex + '.' + ext;
    file.copy(this.createFile_basePath + "/" + template.name, this.coreSvc.path.value.path + "/" + createName).subscribe(s => {
      this.refresh();
    }, e => {
      console.error(e);
    })
  }

  properties() {
    this.dialog.open(PropertiesCmpComponent, {
      data: {
        path: this.coreSvc.path.value.path,
      },
    });
  }

  isCanPaste = false;

  operateMenu(event: MouseEvent) {
    this.isCanPaste = false;
    navigator.clipboard.readText().then(s => {
      this.isCanPaste = s.startsWith("$ispace copy fileBase ") || s.startsWith("$ispace shear fileBase ");
    })
  }

    paste() { 
    navigator.clipboard.readText().then(t=> { 
      let datas = t.replace("\r\n","\n").split("\n");
      datas.forEach(s => {
      let info = s.replace('\r','').split(" "); 
      let path = info[3]
      let fileType = info[4];
      let type = info[1];
      let nameS = path.split("/");
      let name = nameS[nameS.length - 1];
      let data = { type: fileType as 'file'|'folder', path: path,name: name};
      this.paste_one(data,type);
      }) 
    }).catch(e=>{ 
      console.error(e);
    });
  }

  paste_one(data: { type: 'file' | 'folder', path: string, name: string }, type: string) {   
 
      if (data.type == "file") {
        if (type == "copy") {

          file.copy(data.path, this.coreSvc.path.value.path+"/" + data.name).subscribe(s => {
            this.refresh();
          }, e => {
            this.coreSvc.setMsg(e.message);
          });
        }
        if (type == "shear") {
          file.move(data.path, this.coreSvc.path.value.path+"/" + data.name).subscribe(s => {
            this.refresh();
          }, e => {
            this.coreSvc.setMsg(e.message); 
          }
          ) 
        }
      }

      if (data.type == "folder") {
        if (type == "copy") {
          folder.copy(data.path, this.coreSvc.path.value.path+"/" + data.name).subscribe(s => {
            this.refresh();
          }, e => {
            this.coreSvc.setMsg(e.message);
          });
        }
        if (type == "shear") {
          folder.move(data.path, this.coreSvc.path.value.path+"/" + data.name).subscribe(s => {
            this.refresh();
          }, e => {
            this.coreSvc.setMsg(e.message); 
          }
          ) 
        }
      }  
  }

  pasteSymbolicLink() { 
    navigator.clipboard.readText().then(s => {
       
      let info = s.split(" "); 
      let path = info[3]
      let fileType = info[4];
      let type = info[1];
      let nameS = path.split("/");
      let name = nameS[nameS.length - 1];

      if (type == "copy") {
          file.createSymbolicLink(this.coreSvc.path.value.path, "(快捷方式)" + name,path).subscribe(s => {
            this.refresh();
          }, e => {
            this.coreSvc.setMsg(e.message);
          });
      } 

    }).catch(e=>{ 
      console.error(e);
    });
  }


  ext_operations: DriverOperationDto[] = [];
 ext_operations_current: DriverOperationDto[] = [];

  async ext_operation_execute(operation: DriverOperationDto) {
    if(this.coreSvc.env.value == 'desktop' && this.coreSvc.desktopOpenApi.value){ 
      let data = await folder.statf(this.coreSvc.path.value.path).toPromise();
      await this.coreSvc.desktopOpenApi.value!.execute(operation.driverId, operation.id, this.coreSvc.path.value.path,  "folder",data);
    }
    else {
      this.coreSvc.setMsg("当前环境不支持扩展操作");
    }
  }

    async init_ext_operations() {  
    if(this.coreSvc.env.value == 'desktop' && this.coreSvc.desktopOpenApi.value){
      this.ext_operations = await this.coreSvc.desktopOpenApi.value!.getOperations(this.coreSvc.path.value.path,  true);   
        this.ext_operations_current = this.ext_operations.filter(s => s.name !=="打开"&&s.name !=="复制"&&s.name !=="剪切"&&s.name !=="重命名"&&s.name !=="删除"&&s.name !=="属性");
        return;
       }
  } 
}
